<?php
	class Base {
		// public $name = 'test';

		function __construct() {
			header('Access-Control-Allow-Origin: *');
			date_default_timezone_set('PRC'); 
			session_start();
			include_once(dirname(__FILE__) . './errorCode.php');
		}

		// 得到数据库链接
		public function getDB() {
			include_once("MysqliDb.php");
			$server = $_SERVER['SERVER_NAME'];
			if ($server == 'localhost') {
				$host = 'localhost';
				$username = 'root';
				$password = '';
				$db = '80edu';
			} else {
				$host = 'localhost';
				$username = 'zhixinweixue';
				$password = 'Zhixin123!';
				$db = 'zhixinweixue';
			}
			$param = Array (
		      'host' => $host,
		      'username' => $username,
		      'password' => $password,
		      'db'=> $db,
		      'port' => 3306,
		      'charset' => 'utf8'
		  );
		  $db = new MysqliDb($param);
		  return $db;
		}

		// 根据数组，得到返回给前端的json字符串
		public function getResJson($success, $data, $errCode, $message, $arr=null) {
			if (empty($arr)) {
				$arr = Array(
					"success" => $success,
					"message" => $message,
					"errCode" => $errCode,
					"data" => $data
				);
			}
			return json_encode($arr);
		}

		// 检查用户token，并删除过期token
		public function checkToken($token) {
			$db = $this -> getDB();
			$db -> where('token', $token);
			$res = $db -> getOne('tokens');
			if ($res) {
				return true;
			} else {
				return false;
			}
		}

		// 保存用户登录时获得的token
		public function saveToken($token, $uid) {
			$db = $this -> getDB();
			$data = Array (
		  	"token" => $token,
		  	"uid" => $uid
		  );
		  $id = $db->insert('tokens', $data);
		  if ($id > 0) {
		  	return true;
		  } else {
		  	return false;
		  }
		}

		// 根据用户id得到token
		public function getTokenByUid($uid) {
			$db = $this -> getDB();
			$db -> where('uid', $uid);
			$res = $db -> getOne('tokens');
			return $res['token'];
		}
	}
?>